<template>
    <div class="main p-4">
        <div class="title f-16 font-bold mb-4">{{ title }}</div>
        <el-form ref="formRef" :model="formData" label-width="100">
            <el-form-item label="试卷名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="满分">
                <el-input :value="fullScore" disabled placeholder="自动计算" />
            </el-form-item>
            <el-form-item label="难度" prop="difficulty">
                <el-input-number v-model="formData.difficulty" :min="1" placeholder="请输入数字" />
            </el-form-item>
            <el-form-item label="试卷类型" prop="paperType">
                <el-select v-model="formData.paperType" placeholder="">
                  <el-option 
                  v-for="item in paperTypeList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.label"
                  />
                </el-select>
            </el-form-item>
            <el-form-item label="用时(分钟)" prop="useTime">
                <el-input-number v-model="formData.useTime" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="大题" prop="questionsTypeDtos">
                <div class="mt-5 w-full">
                    <Question
                    v-for="(item, i) in formData.questionsTypeDtos"
                    :key="i"
                    :i="i"
                    :questionsTypeList="questionsTypeList"
                    v-model="formData.questionsTypeDtos[i]"
                    :topic-list="topicList"
                    :ref="(el: any) => addQuestionRef(el, item.uid)"
                    @delete="deleteQuestion(item)"
                    />
                    <el-button @click="addBigQuestion" class="w-full mt-4">+ 添加大题</el-button>
                </div>
            </el-form-item>
            <div class="sticky-bottom flex items-center justify-end">
                <el-button @click="cancel">取消</el-button>
                <el-button @click="submit" type="primary">保存</el-button>
            </div>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import request from '@/Utils/request';
import { computed, onActivated, reactive, ref, type VNodeRef } from 'vue';
import { useRoute } from 'vue-router';
import Question from './Children/Question.vue';
import { createUuid, getText } from '@/Utils/utils';
import type { TopicTypeNumber } from '@/Utils/type';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import router from '@/Router';
import { paperTypeListData } from '@/Utils/Data';

interface Questions {
    id: number;
    name: string;
    difficulty: string | number;
    questionsIdList: number[];
    sort?: number;
    everyoneScore: number;
    type: string | TopicTypeNumber;
    uid: string;
}

type QuestionType = InstanceType<typeof Question>;

interface QuestionRef {
    [propName: string]: QuestionType;
};

const formRef = ref<FormInstance>();

const route = useRoute();

const title = computed(() => {
    if (Number(route.params.id) > 0) {
        return '编辑试卷';
    }
    return '新增试卷';
});

const questionsTypeList = ref([
    {
        id: 1,
        label: '填空题'
    },
    {
        id: 2,
        label: '选择题'
    },
    {
        id: 3,
        label: '计算题'
    },
    {
        id: 4,
        label: '应用题'
    },
    {
        id: 5,
        label: '判断题'
    }
]);

const paperTypeList = ref(paperTypeListData);

const formData = reactive({
    difficulty: 1,
    fullScore: 100,
    id: 0,
    name: '',
    useTime: 60,
    paperType: 1,
    questionsTypeDtos: <Questions[]>[
        {
            everyoneScore: 0,
            id: 0,
            name: '',
            difficulty: 1,
            questionsIdList: [],
            type: '',
            uid: createUuid(),
            sort: 1
        }
    ],
});

const topicListData = ref([]);

const questionRefs = reactive<QuestionRef>({});

const topicList = computed(() => topicListData.value.map((item: any) => {
    return {
        value: item.id,
        label: getText(item.content),
        type: item.questionsType
    }
}));

// 满分，自动计算
const fullScore = computed(() => formData.questionsTypeDtos.reduce((total: number, item) => {
    const questionsIdList = item.questionsIdList || [];
    if (questionsIdList.length > 0 && Number(item.everyoneScore) > 0) {
        total += questionsIdList.length * Number(item.everyoneScore);
    }
    return total;
}, 0));

const addQuestionRef = (el: QuestionType, key: string) => {
    questionRefs[key] = el;
    return el as unknown as VNodeRef;
};

// 点击删除大题
const deleteQuestion = async (item: Questions) => {
    try {
        await ElMessageBox.confirm(
            '确认删除试题吗？',
            '提示',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        const index = formData.questionsTypeDtos.findIndex(question => item.uid === question.uid);
        if (index > -1) formData.questionsTypeDtos.splice(index, 1);
        ElMessage({
            message: '删除成功',
            type: 'success'
        });
    } catch (error) {
        
    }
};

// 获取所有试题列表
const getTopicList = async () => {
    try {
        const { records } = await request({
            method: 'post',
            contentTypeIsForm: false,
            errorToast: true,
            data: {
                limit: 9999,
                page: 1
            },
            url: '/questions/list'
        }) || { records: [] };
        topicListData.value = records;
    } catch (error) {
        
    }
};

// 获取试卷
const getDetail = async () => {
    try {
        const paper = await request({
            method: 'post',
            url: '/paper/getOneById',
            contentTypeIsForm: true,
            data: {
                id: formData.id
            },
            showLoading: {}
        });
        formData.difficulty = paper.difficulty;
        formData.fullScore = paper.fullScore;
        formData.name = paper.name;
        formData.useTime = paper.useTime;
        formData.questionsTypeDtos = (paper.questionsTypeVos || []).reduce((list: Questions[], item: any) => {
            list.push({
                ...item,
                questionsIdList: (item.questionsList || []).map((question: any) => Number(question.id)),
                sort: 1
            })
            return list;
        }, []);
    } catch (error) {
        
    }
};

// 点击添加大题
const addBigQuestion = () => {
    formData.questionsTypeDtos.push({
        everyoneScore: 3,
        id: 0,
        name: '',
        difficulty: 1,
        questionsIdList: [],
        type: '',
        uid: createUuid(),
        sort: 1
    });
};

// 点击取消
const cancel = async () => {
    try {
        await ElMessageBox.confirm(
            '确定取消？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        router.back();
    } catch (error) {
        
    }
};

// 点击提交
const submit = async () => {

    try {
        await validate();
        await ElMessageBox.confirm(
            '确定保存？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        let fullScoreTotal = 0;
        const questionsTypeDtos = formData.questionsTypeDtos.map(item => {
            const total = item.everyoneScore * item.questionsIdList.length;
            fullScoreTotal += total;
            return {
                ...item,
                questionsList: undefined,
                fullScore: total
            }
        });
        await request({
            method: 'post',
            url: formData.id > 0 ? '/paper/update' : '/paper/add',
            contentTypeIsForm: false,
            showLoading: {},
            errorToast: true,
            data: {
                ...formData,
                questionsTypeDtos,
                fullScore: fullScoreTotal,
            }
        });
        ElMessage({
            message: '保存成功',
            type: 'success'
        });
        router.back();
    } catch (error) {
        
    }
};

// 校验整个表单
const validate = async () => {
    try {
        await formRef.value?.validate()
        const keys = Object.keys(questionRefs);
        for (let i = 0; i < keys.length; i++) {
            await questionRefs[keys[i]]?.validate();
        }
        return true;
    } catch (error) {
        return false;
    }
};

onActivated(() => {
    getTopicList();
    formData.id = Number(route.params.id) || 0;
    if (formData.id > 0) {
        getDetail();
    }
});
</script>

<style scoped lang="scss">
.main {
    .sticky-bottom {
        height: 60px;
        background-color: rgba(255,255,255,0.9);
    }
}
</style>